//
//  QZFriendDetailsVC.m
//  shortvideoplay
//
//  Created by tikeios_002 on 2024/6/25.
//

#import "QZFriendDetailsVC.h"
#import "XRWaterfallLayout.h"
#import "QZFindsChildCell.h"
#import "SYCollectionViewRoundFlowLayout.h"
#import "QZMyDetailsPlayVC.h"
#import "CSJADLoading.h"
#import "GDTNativeExpressAdView.h"
//#import "DJMyVideoPlayVC.h"

@interface QZFriendDetailsVC ()<UICollectionViewDelegate,UICollectionViewDataSource,XRWaterfallLayoutDelegate,BUNativeExpressAdViewDelegate>
@property (strong, nonatomic)  UICollectionView *historyCollection;
@property (strong,nonatomic)NSMutableArray <QZVideoModel *>* listArr;
@property (strong,nonatomic) PublicView * nullView;
@property (assign,nonatomic) NSInteger page;
@property (assign, nonatomic) CGFloat itemWidth;
@property (assign, nonatomic) CGFloat itemHeight;
@property (nonatomic, strong) NSString *videoIdsStr;
@property (nonatomic, strong) BUNativeExpressAdManager * nativeExpressAdManager;
@property (assign, nonatomic) NSInteger adRow;
@end

@implementation QZFriendDetailsVC

-(void)showTextViewNavViewTo1{
    NSMutableArray * showTextViewNavViewNameArrTo1 = [NSMutableArray new];
    UIView * showTextViewNavViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewNavViewViewTo1.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewNavViewViewTo1];
    UILabel * showTextViewNavViewLabelTo1 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    NSInteger showTextViewNavViewNumberTo1 = arc4random_uniform(20);
    NSLog(@"：%ld", (long)showTextViewNavViewNumberTo1);
    showTextViewNavViewLabelTo1.text = [NSString stringWithFormat:@"%ld",(long)showTextViewNavViewNumberTo1];
    [showTextViewNavViewLabelTo1 addSubview:showTextViewNavViewLabelTo1];
    
    UIImageView * showTextViewNavViewLabelTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [showTextViewNavViewViewTo1 addSubview:showTextViewNavViewLabelTo2];
    
}
- (void)showOldAddNavViewToMainOldView1{
    UIView * oldBgSS = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    oldBgSS.clipsToBounds = YES;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:oldBgSS];
    
    UIButton * sendBtn = [[UIButton alloc]initWithFrame:CGRectMake(KScreen_W-75, kStatusBarHeight+10, 60, 46)];
    sendBtn.layer.cornerRadius = 3;
    sendBtn.backgroundColor = [UIColor whiteColor];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:ColorHex(@"#333333") forState:UIControlStateNormal];
    sendBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [sendBtn addTarget:self action:@selector(sendTap) forControlEvents:UIControlEventTouchUpInside];
    [oldBgSS addSubview:sendBtn];
    
    UIView * sendBg = [[UIView alloc]initWithFrame:CGRectMake(15, kStatusBarHeight+66, KScreen_W-30, (KScreen_H-KSafeAreaBottomHeight-25-(kStatusBarHeight+66))/2)];
    sendBg.backgroundColor = [UIColor whiteColor];
    sendBg.layer.cornerRadius = 3;
    [oldBgSS addSubview:sendBg];
    
    UILabel * sendTip = [[UILabel alloc]initWithFrame:CGRectMake(0, (sendBg.frame.size.height-40)/2, sendBg.frame.size.width, 40)];
    sendTip.text = @"发送区";
    sendTip.textColor = ColorHex(@"#f0f0f0");
    sendTip.textAlignment = NSTextAlignmentCenter;
    sendTip.font = [UIFont systemFontOfSize:28];
    [sendBg addSubview:sendTip];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = viewback_black;
    self.adRow = 2;
    self.itemWidth = (KScreen_W-3)/2;
    self.itemHeight = self.itemWidth/0.9;
    _videoIdsStr = @"";
    KWeakSelf
    self.historyCollection.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page = weakSelf.page+1;
        [weakSelf getHistoryVideoList];
    }];
    self.historyCollection.mj_header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        //下拉刷新要做的操作.
        [weakSelf.historyCollection.mj_footer resetNoMoreData];
        [weakSelf.listArr removeAllObjects];
        [weakSelf.historyCollection reloadData];
        weakSelf.adRow = 2;
        weakSelf.page = 0;
        weakSelf.videoIdsStr = @"";
        [weakSelf getHistoryVideoList];
    }];
    [SVProgressHUDTool showWithStatus:nil];
    [self getHistoryVideoList];
//    [self AdLoading];
    [[QZDataUpdate share] addListenerObj:self];
}
#pragma mark 刷新
- (NSMutableArray *)sourceData{
    return self.listArr;
}
- (void)updateData:(QZVideoModel *)data index:(NSInteger)index type:(QZDataUpdateType)type{
    [self.historyCollection reloadData];
}
#pragma mark 懒加载
- (NSMutableArray *)showTextViewToKey1:(NSString *)keyString{
    NSMutableArray *showTextViewArrTo1 = [NSMutableArray new];
    for (int i = 0; [showTextViewArrTo1 count] < 5; i++) {
        int  RandomNumber = arc4random() % 30;
        if(![showTextViewArrTo1 containsObject:[NSNumber numberWithInt:RandomNumber]]){
            [showTextViewArrTo1 addObject:[NSNumber numberWithInt:RandomNumber]];
        }
    }
    return showTextViewArrTo1;
}
- (NSInteger)showTextViewToTime1:(NSString *)time{
    NSDateFormatter *showTextViewFaTo1 = [[NSDateFormatter alloc] init];
    [showTextViewFaTo1 setDateFormat:@"yyyy-MM-dd"];
    return [[showTextViewFaTo1 dateFromString:time] timeIntervalSince1970];
}
- (NSMutableArray *)listArr{
    if(_listArr == nil){
        _listArr = [NSMutableArray new];
    }
    return _listArr;
}
- (UICollectionView *)historyCollection{
    if(_historyCollection == nil){
        //创建瀑布流布局
        XRWaterfallLayout *waterfall = [XRWaterfallLayout waterFallLayoutWithColumnCount:2];
        //或者一次性设置
        [waterfall setColumnSpacing:3 rowSpacing:3 sectionInset:UIEdgeInsetsMake(5, 0, KSafeAreaBottomHeight+5, 0)];
        //设置代理，实现代理方法
        waterfall.delegate = self;
//        SYCollectionViewRoundFlowLayout *layout = [[SYCollectionViewRoundFlowLayout alloc]init];
//        layout.sectionHeadersPinToVisibleBounds = YES;
//        layout.collectionCellAlignmentType = SYCollectionViewFlowLayoutAlignmentTypeByLeft;
        _historyCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, KScreen_W, KScreen_H-KNav_H-KTab_H) collectionViewLayout:waterfall];
        [_historyCollection registerClass:[QZFindsChildCell class] forCellWithReuseIdentifier:@"QZFindsChildCell"];
        _historyCollection.backgroundColor = viewback_black;
  
        _historyCollection.alwaysBounceVertical = YES;
        _historyCollection.collectionViewLayout = waterfall;
        _historyCollection.delegate = self;
        _historyCollection.dataSource = self;
           UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:_historyCollection];
    }
    return _historyCollection;
}
- (PublicView *)nullView{
    if(_nullView == nil){
        _nullView = [[PublicView alloc]initWithFrame:CGRectMake(0, (KScreen_H-KNav_H-200)/2, KScreen_W, 200)];
        _nullView.publicLabel.text = @"暂无数据";
        _nullView.hidden = YES;
        _nullView.userInteractionEnabled = NO;
           UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:_nullView];
    }
    return _nullView;
}
#pragma mark 请求区域
- (void)getHistoryVideoList{
    KWeakSelf
    KMutableDic(sendDic)
    sendDic[@"page"] = @(self.page);
    sendDic[@"page_num"] = @(20);
    if (_videoIdsStr.length > 0) {
        [sendDic setObject:[self.videoIdsStr substringWithRange:NSMakeRange(0, self.videoIdsStr.length-1)] forKey:@"videoids"];
    }

    if (_typeName != nil) {
        [sendDic setObject:_typeName forKey:@"types"];
    }
    NSLog(@"=====%ld",(long)self.page);
    [YBNetBase videoTypeSelectRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
        if(code == 200){
            CGFloat maxLineHeight = Font(14).lineHeight * 3;
            NSArray * list = data[@"list"];
            int index = 0;
            for (NSInteger i=weakSelf.adRow; i<weakSelf.listArr.count+list.count-1; i++) {
                index++;
                i=i+5;
            }
            for (NSDictionary * dic in data[@"list"]) {
                if(![dic[@"video_url"] isKindOfClass:[NSDictionary class]] || dic[@"video_url"] == nil ||[dic[@"video_url"] allKeys].count == 0){
                    continue;
                }
                QZVideoModel * model = [[QZVideoModel alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                CGFloat introHeight = [Tools getTextHeightWithText:model.introduce width:weakSelf.itemWidth-20 maxHeight: maxLineHeight font:Font(14)] + 2;
                
                CGFloat imageH;
                if([model.height floatValue] > [model.width floatValue]){
                    imageH = self.itemWidth/3*4;
                }else{
                    imageH = self.itemWidth/4*3;
                }
                weakSelf.videoIdsStr = [NSString stringWithFormat:@"%@%@,",weakSelf.videoIdsStr,model.videoid];
                model.itemSize = CGSizeMake(weakSelf.itemWidth, introHeight+imageH+56);
                [weakSelf.listArr addObject:model];
            }
            if([data[@"list"] count] != 0 && index != 0){
                [weakSelf adRequest:index list:list];
            }else{
                [weakSelf requestEnd:data[@"list"]];
            }
            
        }else{
            [SVProgressHUDTool dismiss];
            [YBMsgPop showPop:msg];
        }
    }];
}
- (void)adRequest:(NSInteger)number list:(NSArray *)list{
    KWeakSelf
    [CSJADLoading share].ADNativeAdsLoadFish = ^(NSArray * _Nullable nativeAdDataArray, NSInteger type) {
        [nativeAdDataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            QZVideoModel * model = [[QZVideoModel alloc]init];
            if(type == 0){
                BUNativeExpressAdView *expressView = (BUNativeExpressAdView *)obj;
                expressView.backgroundColor = UIColor.whiteColor;
                expressView.rootViewController = self;
                // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                [expressView render];
                model.expressView2 = expressView;
            }else{
                GDTNativeExpressAdView *expressView = (GDTNativeExpressAdView *)obj;
                expressView.controller = weakSelf;
                expressView.backgroundColor = UIColor.whiteColor;
                // important: 此处会进行WKWebview的渲染，建议一次最多预加载三个广告，如果超过3个会很大概率导致WKWebview渲染失败。
                [expressView render];
                model.expressView2 = expressView;
            }
            model.itemSize = CGSizeMake(weakSelf.itemWidth, weakSelf.itemWidth);
            model.is_ADView = YES;
            [weakSelf.listArr insertObject:model atIndex:weakSelf.adRow];
            weakSelf.adRow = weakSelf.adRow+7;
            if(weakSelf.adRow >= weakSelf.listArr.count ){
                [weakSelf requestEnd:list];
                return;
            }
        }];
        if(nativeAdDataArray.count < number && nativeAdDataArray.count != 0){
            [weakSelf adRequest:number-3 list:list];
        }else{
            [weakSelf requestEnd:list];
        }
        
    };
    if(number > 3){
        [CSJADLoading ADNativeAdsAdPhoneRequest:3];
    }else{
        [CSJADLoading ADNativeAdsAdPhoneRequest:number];
    }
    
}
- (void)requestEnd:(NSArray *)list{
    [SVProgressHUDTool dismiss];
    [self.historyCollection reloadData];
    if([self.historyCollection.mj_header isRefreshing]){
        [self.historyCollection.mj_header endRefreshing];
    }else if ([self.historyCollection.mj_footer isRefreshing]){
        if([list count] == 0){
            [self.historyCollection.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.historyCollection.mj_footer endRefreshing];
        }
    }else{
        if(self.listArr.count == 0){
            self.nullView.hidden = NO;
            self.historyCollection.mj_footer.hidden = YES;
        }else{
            self.nullView.hidden = YES;
            self.historyCollection.mj_footer.hidden = NO;
        }
    }
}
-(void)showTextViewAddShowViewTo2{
    UIView * showTextViewViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 20, 100, 360)];
    showTextViewViewTo1.backgroundColor = [UIColor whiteColor];
    showTextViewViewTo1.layer.cornerRadius = 8;
       UILabel * oldshowSSSSTip = [[UILabel alloc]init];
    oldshowSSSSTip.clipsToBounds = YES;
    oldshowSSSSTip.text = @"kass显示区";
    oldshowSSSSTip.textColor = ColorHex(@"#f0f0f0");
    oldshowSSSSTip.textAlignment = NSTextAlignmentCenter;
    oldshowSSSSTip.font = [UIFont systemFontOfSize:28];
    oldshowSSSSTip.hidden = YES;
    [self.view addSubview:oldshowSSSSTip];
    [self.view addSubview:showTextViewViewTo1];
    
    UIImageView * showTextViewimgTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(K_AUTOLAYOUT_W(157.5), K_AUTOLAYOUT_W(260), K_AUTOLAYOUT_W(60), K_AUTOLAYOUT_W(60))];
    showTextViewimgTo2.layer.cornerRadius = K_AUTOLAYOUT_W(30);
    showTextViewimgTo2.clipsToBounds = YES;
    showTextViewimgTo2.contentMode = UIViewContentModeScaleAspectFill;
    showTextViewimgTo2.hidden = YES;
    [showTextViewViewTo1 addSubview:showTextViewimgTo2];
    
    UILabel *  showTextViewimgTo3 = [[UILabel alloc]initWithFrame:CGRectMake(K_AUTOLAYOUT_W(15), K_AUTOLAYOUT_W(35), K_AUTOLAYOUT_W(345), K_AUTOLAYOUT_W(25))];
    showTextViewimgTo3.font = FontBold(18);
    showTextViewimgTo3.textColor = ThreeColor;
    showTextViewimgTo3.textAlignment = NSTextAlignmentCenter;
    showTextViewimgTo3.hidden = YES;
    [showTextViewViewTo1 addSubview:showTextViewimgTo3];
}
- (NSString *)showTextViewGetNowTimerTo3{
    NSDateFormatter *showTextViewGetNowFa = [[NSDateFormatter alloc] init];
    [showTextViewGetNowFa setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    return [showTextViewGetNowFa stringFromDate:[NSDate date]];
}

- (void)tableEndFiresh{
    if([self.historyCollection.mj_header isRefreshing]){
        [self.historyCollection.mj_header endRefreshing];
    }
    if([self.historyCollection.mj_footer isRefreshing]){
        [self.historyCollection.mj_footer endRefreshing];
    }
}
#pragma mark 事件区域
- (void)historyRemove{
    KWeakSelf
    [[BSystemAlert shared] showAlertWithTitle:@"温馨提示" message:@"是否确定清除所有历史观看记录？" userData:nil cancelTitle:@"取消" actions:@[@"清除"] actionBlock:^(id  _Nonnull userData, NSString * _Nonnull actionTitle) {
        if([actionTitle isEqualToString:@"清除"]){
            KMutableDic(sendDic)
            [YBNetBase historyVideoRemoveRequest:sendDic successBlock:^(NSDictionary * _Nonnull data, NSInteger code, NSString * _Nonnull msg) {
                if(code == 200){
                    [weakSelf.listArr removeAllObjects];
                    [weakSelf.historyCollection reloadData];
                    weakSelf.nullView.hidden = NO;
                }else{
                    [YBMsgPop showPop:msg];
                }
            }];
        }
    }];
}
#pragma mark collectionDelege
//根据item的宽度与indexPath计算每一个item的高度
- (CGFloat)waterfallLayout:(XRWaterfallLayout *)waterfallLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath {

    return self.listArr[indexPath.row].itemSize.height;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.listArr.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    QZFindsChildCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"QZFindsChildCell" forIndexPath:indexPath];
    [cell findsShoeCell:self.listArr[indexPath.row]];
    return cell;
}

- (void)showTextViewSubViewToViewTo1:(UIView * )subView{

    UIView * showTextViewSubViewTo1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
    showTextViewSubViewTo1.clipsToBounds = YES;
    [subView addSubview:showTextViewSubViewTo1];
    UILabel * showTextViewSubViewLabelTo2 = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    showTextViewSubViewLabelTo2.text = @"56464645";
    [showTextViewSubViewTo1 addSubview:showTextViewSubViewLabelTo2];
    
    UIImageView * showTextViewSubViewTo2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    [subView addSubview:showTextViewSubViewTo2];

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    QZMyDetailsPlayVC * play = [[QZMyDetailsPlayVC alloc]init];
    play.isAdShow = YES;
    play.videoArr = [[NSMutableArray alloc]initWithArray:self.listArr];
    play.videoPlayIndex = indexPath.row;
    [self.navigationController pushViewController:play animated:YES];
}
- (void)AdLoading{

    
    
    BUAdSlot *adSlot = [[BUAdSlot alloc] init];
    adSlot.ID = @"959027546";
    adSlot.AdType = BUAdSlotAdTypeFeed; //required
    adSlot.position = BUAdSlotPositionFeed;
    adSlot.imgSize = [BUSize sizeBy:BUProposalSize_DrawFullScreen];
    self.nativeExpressAdManager = [[BUNativeExpressAdManager alloc] initWithSlot:adSlot adSize:CGSizeMake(self.itemWidth, self.itemHeight)];
         
    // 配置：回调代理对象
    self.nativeExpressAdManager.adSize = CGSizeMake(self.itemWidth, self.itemHeight);
    self.nativeExpressAdManager.delegate = self;
    [self.nativeExpressAdManager loadAdDataWithCount:1];
    
}
// 收到load成功回调后展示
# pragma mark ---<BUMNativeAdsManagerDelegate>---
- (void)nativeExpressAdSuccessToLoad:(BUNativeExpressAdManager *)nativeExpressAd views:(NSArray<__kindof BUNativeExpressAdView *> *)views {

    if (views.count) {

    }
}
- (void)nativeExpressAdFailToLoad:(BUNativeExpressAdManager *)nativeExpressAd error:(NSError *)error {

}
#pragma mark CategoryListContentViewDelegate
- (UIView *)listView {
    return self.view;
}
@end
